package com.usian.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.usian.pojo.Result;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import java.util.logging.LogRecord;

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] urls = {"/backend/**", "/front/**", "/employee/login"};
        boolean flag = checkUrl(urls, requestURI);
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("employee") != null) {
            filterChain.doFilter(request, response);
            return;
        }
        String json = JSON.toJSONString(Result.error("NOTLOGIN"));
        response.getWriter().write(json);

    }
    private boolean checkUrl(String[] urls, String requestURI) {

        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }

}
